package com.example.xxcjgl.data.repository

import com.example.xxcjgl.data.models.LoginRequest
import com.example.xxcjgl.data.models.Resource
import com.example.xxcjgl.data.models.Student
import com.example.xxcjgl.data.models.User
import com.example.xxcjgl.utils.EncryptionUtils
import com.example.xxcjgl.utils.PreferencesManager
import javax.inject.Inject
import com.example.xxcjgl.data.api.ApiService
import com.google.gson.annotations.SerializedName

class UserRepository @Inject constructor(
    private val apiService: ApiService,
    private val preferencesManager: PreferencesManager
) {
    suspend fun login(username: String, password: String, captcha: String): Resource<User> {
        return try {
            val hashedPassword = EncryptionUtils.hashPassword(password)
            val response = apiService.login(LoginRequest(username, hashedPassword, captcha))

            if (response.success && response.data != null) {
                preferencesManager.saveUser(response.data)
                preferencesManager.setLoggedIn(true)
                Resource.Success(response.data)
            } else {
                Resource.Error(response.message ?: "登录失败")
            }
        } catch (e: Exception) {
            Resource.Error("网络连接失败: ${e.message}")
        }
    }

    suspend fun getStudents(keyword: String): Resource<List<Student>> {
        return try {
            val response = apiService.getStudents(keyword)
            if (response.success) {
                Resource.Success(response.data ?: emptyList())
            } else {
                Resource.Error(response.message ?: "获取学生列表失败")
            }
        } catch (e: Exception) {
            Resource.Error("网络错误: ${e.message}")
        }
    }

    suspend fun addStudent(student: Student): Resource<Boolean> {
        return try {
            val response = apiService.addStudent(student)
            if (response.success) {
                Resource.Success(true)
            } else {
                Resource.Error(response.message ?: "添加学生失败")
            }
        } catch (e: Exception) {
            Resource.Error("网络错误: ${e.message}")
        }
    }

    suspend fun addScore(score: Student): Resource<Boolean> {
        return try {
            // 如果需要加密，在这里处理加密逻辑
            val finalScore = if (score.encryptionFlag == 1) {
                score.copy(
                    mathScore = encryptScore(score.mathScore, score.encryptionKey),
                    chineseScore = encryptScore(score.chineseScore, score.encryptionKey)
                )
            } else {
                score
            }

            val response = apiService.addScore(finalScore)
            if (response.success) {
                Resource.Success(true)
            } else {
                Resource.Error(response.message ?: "保存成绩失败")
            }
        } catch (e: Exception) {
            Resource.Error("网络错误: ${e.message}")
        }
    }

    private fun encryptScore(score: Float?, key: String?): Float? {
        if (score == null || key.isNullOrBlank()) return score
        val encrypted = EncryptionUtils.encrypt(score.toString(), key)
        return encrypted?.hashCode()?.toFloat() // 简化处理，实际应该存储加密后的字符串
    }

    fun getCurrentUser(): User? {
        return preferencesManager.getCurrentUser()
    }

    fun logout() {
        preferencesManager.clearUserData()
    }

    fun shouldAutoLogin(): Boolean {
        return preferencesManager.isLoggedIn() && preferencesManager.shouldRememberMe()
    }
}